﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using Bricks.Component.Utils;
using Bricks.Business.Models;
using Bricks.Business.Models.FlowProcess;
using Bricks.Site.Models;
using Bricks.Business.Data.Repositories.ScheduleManagement;
using System.Xml;
using Bricks.Business.Service;
using Bricks.Business.Models.ScheduleManagement;


namespace ChiDao.Business.Service.Impl
{
    [Export(typeof(IStatisticsItemMaintenanceService))]
    internal class StatisticsItemMaintenanceService : IStatisticsItemMaintenanceService
    {
        #region 属性
        [Import]
        protected IStatisticsItemMaintenanceRepository StatisticsItemMaintenanceRepository { get; set; }
        [Import]
        protected ITotalMaintenanceDetailsRepository TotalMaintenanceDetailsRepository { get; set; }
        [Import]
        protected ITotalReviseDetailsRepository TotalReviseDetailsRepository { get; set; }
        [Import]
        protected IYearPlanDetailsRepository YearPlanDetailsRepository { get; set; }
        [Import]
        protected IYearPlanReviseDetailsRepository YearPlanReviseDetailsRepository { get; set; }
        [Import]
        protected IMonthPlanDetailsRepository MonthPlanDetailsRepository { get; set; }
        #endregion

        public IQueryable<StatisticsItemMaintenance> StatisticsItemMaintenances
        {
            get { return StatisticsItemMaintenanceRepository.Entities; }
        }

        #region 主界面加载
        public List<StatisticsItemMaintenanceView> GetStatisticsItemMaintenanceList(Guid projectID, string contractType)
        {
            List<StatisticsItemMaintenanceView> lstStatisticsItemMaintenanceView = new List<StatisticsItemMaintenanceView>();
            IQueryable<StatisticsItemMaintenance> statisticsItemMaintenances = StatisticsItemMaintenanceRepository.Entities.Where(s => s.ProjectID == projectID && s.ContractType == contractType);
            foreach (StatisticsItemMaintenance statisticsItemMaintenance in statisticsItemMaintenances)
            {
                string parentStatisticsItemName = statisticsItemMaintenance.StatisticsItemName;
                if (statisticsItemMaintenance.IsParent)
                {
                    IQueryable<StatisticsItemMaintenance> parentStatisticsItemMaintenances = statisticsItemMaintenances.Where(s => s.PID == statisticsItemMaintenance.ID);
                    if (parentStatisticsItemMaintenances.Count() == 0)
                    {
                        lstStatisticsItemMaintenanceView.Add(ConstructView(statisticsItemMaintenance, parentStatisticsItemName, true, true));
                    }
                }
                else
                {
                    if (statisticsItemMaintenance.PID != null)
                    {
                        parentStatisticsItemName = GetParentStatisticsItemName(statisticsItemMaintenance.PID);
                    }
                    if (!string.IsNullOrEmpty(statisticsItemMaintenance.EngineeringUnit))
                    {
                        lstStatisticsItemMaintenanceView.Add(ConstructView(statisticsItemMaintenance, parentStatisticsItemName, false, true));
                    }
                    if (!string.IsNullOrEmpty(statisticsItemMaintenance.MoneyUnit))
                    {
                        lstStatisticsItemMaintenanceView.Add(ConstructView(statisticsItemMaintenance, parentStatisticsItemName, false, false));
                    }
                }
            }
            return lstStatisticsItemMaintenanceView.OrderBy(s => s.OrderNo).ToList();
        }

        private string GetParentStatisticsItemName(Guid? PID)
        {
            string parentStatisticsItemName = string.Empty;
            StatisticsItemMaintenance parentStatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.SingleOrDefault(s => s.ID == PID);
            if (parentStatisticsItemMaintenance != null)
            {
                parentStatisticsItemName = parentStatisticsItemMaintenance.StatisticsItemName;
            }
            return parentStatisticsItemName;
        }

        private StatisticsItemMaintenanceView ConstructView(StatisticsItemMaintenance statisticsItemMaintenance, string parentStatisticsItemName, bool isParent, bool isEngineeringUnit)
        {
            StatisticsItemMaintenanceView statisticsItemMaintenanceView = new StatisticsItemMaintenanceView();
            statisticsItemMaintenanceView.ID = statisticsItemMaintenance.ID;
            statisticsItemMaintenanceView.ProjectID = statisticsItemMaintenance.ProjectID;
            statisticsItemMaintenanceView.ContractType = statisticsItemMaintenance.ContractType;
            statisticsItemMaintenanceView.StatisticsItemCode = statisticsItemMaintenance.StatisticsItemCode;
            statisticsItemMaintenanceView.StatisticsItemName = statisticsItemMaintenance.StatisticsItemName;
            statisticsItemMaintenanceView.IsParent = statisticsItemMaintenance.IsParent;
            statisticsItemMaintenanceView.PID = statisticsItemMaintenance.PID;
            statisticsItemMaintenanceView.EngineeringUnit = statisticsItemMaintenance.EngineeringUnit;
            statisticsItemMaintenanceView.MoneyUnit = statisticsItemMaintenance.MoneyUnit;
            statisticsItemMaintenanceView.OrderNo = statisticsItemMaintenance.OrderNo;
            statisticsItemMaintenanceView.ParentStatisticsItemName = parentStatisticsItemName;
            if (!isParent)
            {
                if (isEngineeringUnit)
                {
                    statisticsItemMaintenanceView.Unit = statisticsItemMaintenance.EngineeringUnit;
                }
                else
                {
                    statisticsItemMaintenanceView.Unit = statisticsItemMaintenance.MoneyUnit;
                }
            }
            return statisticsItemMaintenanceView;
        }
        #endregion

        #region 获取父项
        public List<StatisticsItemMaintenanceView> GetParentStatisticsItemMaintenanceList(Guid projectID, string contractType)
        {
            List<StatisticsItemMaintenanceView> lstStatisticsItemMaintenanceView = new List<StatisticsItemMaintenanceView>();
            lstStatisticsItemMaintenanceView.Add(new StatisticsItemMaintenanceView()
            {
                ID = Guid.Empty,
                StatisticsItemName = "无父项"
            });
            IQueryable<StatisticsItemMaintenance> statisticsItemMaintenances = StatisticsItemMaintenanceRepository.Entities.Where(s => s.ProjectID == projectID && s.ContractType == contractType && s.IsParent == true).OrderBy(s => s.OrderNo);
            foreach (StatisticsItemMaintenance statisticsItemMaintenance in statisticsItemMaintenances)
            {
                lstStatisticsItemMaintenanceView.Add(new StatisticsItemMaintenanceView()
                {
                    ID = statisticsItemMaintenance.ID,
                    StatisticsItemName = statisticsItemMaintenance.StatisticsItemName
                });
            }
            return lstStatisticsItemMaintenanceView;
        }
        #endregion

        #region 单据加载
        public StatisticsItemMaintenanceView GetStatisticsItemMaintenance(Guid id)
        {
            StatisticsItemMaintenanceView statisticsItemMaintenanceView = null;
            StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.FirstOrDefault(a => a.ID == id);
            if (statisticsItemMaintenance != null)
            {
                statisticsItemMaintenanceView = new StatisticsItemMaintenanceView();
                statisticsItemMaintenanceView.ID = statisticsItemMaintenance.ID;
                statisticsItemMaintenanceView.ProjectID = statisticsItemMaintenance.ProjectID;
                statisticsItemMaintenanceView.ContractType = statisticsItemMaintenance.ContractType;
                statisticsItemMaintenanceView.StatisticsItemCode = statisticsItemMaintenance.StatisticsItemCode;
                statisticsItemMaintenanceView.StatisticsItemName = statisticsItemMaintenance.StatisticsItemName;
                statisticsItemMaintenanceView.IsParent = statisticsItemMaintenance.IsParent;
                statisticsItemMaintenanceView.PID = statisticsItemMaintenance.PID;
                statisticsItemMaintenanceView.EngineeringUnit = statisticsItemMaintenance.EngineeringUnit;
                statisticsItemMaintenanceView.MoneyUnit = statisticsItemMaintenance.MoneyUnit;
                statisticsItemMaintenanceView.OrderNo = statisticsItemMaintenance.OrderNo;
                string parentStatisticsItemName = string.Empty;
                if (statisticsItemMaintenance.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(statisticsItemMaintenance.PID);
                }
                statisticsItemMaintenanceView.ParentStatisticsItemName = parentStatisticsItemName;
            }
            return statisticsItemMaintenanceView;
        }
        #endregion

        #region 保存
        public OperationResult SaveStatisticsItemMaintenance(StatisticsItemMaintenanceView statisticsItemMaintenanceView)
        {
            try
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.FirstOrDefault(a => a.ID == statisticsItemMaintenanceView.ID);
                if (statisticsItemMaintenance == null)
                {
                    Add(statisticsItemMaintenanceView);
                }
                else
                {
                    if (IsBeRef(statisticsItemMaintenanceView) == "0")
                    {
                        Modify(statisticsItemMaintenance, statisticsItemMaintenanceView);
                    }
                    else
                    {
                        return new OperationResult(OperationResultType.IsBeRef, "被其他模块引用");
                    }
                }
                return new OperationResult(OperationResultType.Success, "操作成功");
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
        }

        private void Add(StatisticsItemMaintenanceView statisticsItemMaintenanceView)
        {
            StatisticsItemMaintenance record = new StatisticsItemMaintenance();
            record.ID = statisticsItemMaintenanceView.ID;
            record.ProjectID = statisticsItemMaintenanceView.ProjectID;
            record.ContractType = statisticsItemMaintenanceView.ContractType;
            record.StatisticsItemCode = statisticsItemMaintenanceView.StatisticsItemCode;
            record.StatisticsItemName = statisticsItemMaintenanceView.StatisticsItemName;
            record.IsParent = statisticsItemMaintenanceView.IsParent;
            record.PID = statisticsItemMaintenanceView.PID;
            record.EngineeringUnit = statisticsItemMaintenanceView.EngineeringUnit;
            record.MoneyUnit = statisticsItemMaintenanceView.MoneyUnit;
            record.OrderNo = StatisticsItemMaintenanceRepository.GetNextOrderNo(p => p.OrderNo);
            StatisticsItemMaintenanceRepository.Insert(record);
        }

        public string IsBeRef(StatisticsItemMaintenanceView model)
        {
            StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.FirstOrDefault(a => a.ID == model.ID);
            if (statisticsItemMaintenance != null)
            {
                if (model.EngineeringUnit != statisticsItemMaintenance.EngineeringUnit || model.MoneyUnit != statisticsItemMaintenance.MoneyUnit || (model.IsParent == true && statisticsItemMaintenance.IsParent == false))
                {
                    IQueryable<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(t => t.StatisticsItemID == model.ID);
                    if (lstTotalMaintenanceDetail.Count() > 0)
                    {
                        return "1";
                    }

                    IQueryable<YearPlanDetails> lstYearPlanDetail = YearPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == model.ID);
                    if (lstYearPlanDetail.Count() > 0)
                    {
                        return "1";
                    }

                    IQueryable<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == model.ID);
                    if (lstMonthPlanDetail.Count() > 0)
                    {
                        return "1";
                    }
                }
            }

            return "0";
        }

        private void Modify(StatisticsItemMaintenance record, StatisticsItemMaintenanceView statisticsItemMaintenanceView)
        {
            record.StatisticsItemCode = statisticsItemMaintenanceView.StatisticsItemCode;
            record.StatisticsItemName = statisticsItemMaintenanceView.StatisticsItemName;
            record.IsParent = statisticsItemMaintenanceView.IsParent;
            record.PID = statisticsItemMaintenanceView.PID;
            record.EngineeringUnit = statisticsItemMaintenanceView.EngineeringUnit;
            record.MoneyUnit = statisticsItemMaintenanceView.MoneyUnit;
            StatisticsItemMaintenanceRepository.Update(record);
        }


        public OperationResult SaveStatisticsItemMaintenanceAndDeleteRefData(StatisticsItemMaintenanceView statisticsItemMaintenanceView)
        {
            try
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.FirstOrDefault(a => a.ID == statisticsItemMaintenanceView.ID);
                if (statisticsItemMaintenance != null)
                {
                    Modify(statisticsItemMaintenance, statisticsItemMaintenanceView);
                    DeleteRefData(statisticsItemMaintenance.ID);
                }
                return new OperationResult(OperationResultType.Success, "操作成功");
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
        }

        private void DeleteRefData(Guid statisticsItemMaintenanceID)
        {
            List<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenanceID).ToList();
            foreach (TotalMaintenanceDetails totalMaintenanceDetails in lstTotalMaintenanceDetail)
            {
                TotalMaintenanceDetailsRepository.Delete(totalMaintenanceDetails.ID);
            }

            List<TotalReviseDetails> lstTotalReviseDetail = TotalReviseDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenanceID).ToList();
            foreach (TotalReviseDetails totalReviseDetails in lstTotalReviseDetail)
            {
                TotalReviseDetailsRepository.Delete(totalReviseDetails.ID);
            }

            List<YearPlanDetails> lstYearPlanDetail = YearPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenanceID).ToList();
            foreach (YearPlanDetails yearPlanDetails in lstYearPlanDetail)
            {
                YearPlanDetailsRepository.Delete(yearPlanDetails.ID);
            }

            List<YearPlanReviseDetails> lstYearPlanReviseDetail = YearPlanReviseDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenanceID).ToList();
            foreach (YearPlanReviseDetails yearPlanReviseDetails in lstYearPlanReviseDetail)
            {
                YearPlanReviseDetailsRepository.Delete(yearPlanReviseDetails.ID);
            }

            List<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenanceID).ToList();
            foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetail)
            {
                MonthPlanDetailsRepository.Delete(monthPlanDetails.ID);
            }
        }
        #endregion

        #region 拷贝新增
        public OperationResult SaveCopyStatisticsItemMaintenance(Guid projectID, string contractType, Guid copyProjectID, string copyContractType)
        {
            try
            {
                List<StatisticsItemMaintenanceView> lstStatisticsItemMaintenanceView = new List<StatisticsItemMaintenanceView>();
                IQueryable<StatisticsItemMaintenance> copyStatisticsItemMaintenances = StatisticsItemMaintenanceRepository.Entities.Where(s => s.ProjectID == copyProjectID && s.ContractType == copyContractType).OrderBy(s => s.OrderNo);
                foreach (StatisticsItemMaintenance copyStatisticsItemMaintenance in copyStatisticsItemMaintenances)
                {
                    lstStatisticsItemMaintenanceView.Add(new StatisticsItemMaintenanceView()
                    {
                        ID = copyStatisticsItemMaintenance.ID,
                        ProjectID = projectID,
                        ContractType = contractType,
                        StatisticsItemCode = copyStatisticsItemMaintenance.StatisticsItemCode,
                        StatisticsItemName = copyStatisticsItemMaintenance.StatisticsItemName,
                        IsParent = copyStatisticsItemMaintenance.IsParent,
                        PID = copyStatisticsItemMaintenance.PID,
                        EngineeringUnit = copyStatisticsItemMaintenance.EngineeringUnit,
                        MoneyUnit = copyStatisticsItemMaintenance.MoneyUnit
                    });
                }

                foreach (StatisticsItemMaintenanceView statisticsItemMaintenanceView in lstStatisticsItemMaintenanceView)
                {
                    Guid oldID = statisticsItemMaintenanceView.ID;
                    Guid newID = GuidHelper.NewGuid();
                    statisticsItemMaintenanceView.ID = newID;
                    if (statisticsItemMaintenanceView.IsParent)
                    {
                        IEnumerable<StatisticsItemMaintenanceView> lstSubStatisticsItemMaintenanceView = lstStatisticsItemMaintenanceView.Where(s => s.PID == oldID);
                        foreach (StatisticsItemMaintenanceView subStatisticsItemMaintenanceView in lstSubStatisticsItemMaintenanceView)
                        {
                            subStatisticsItemMaintenanceView.PID = newID;
                        }
                    }
                }

                foreach (StatisticsItemMaintenanceView statisticsItemMaintenanceView in lstStatisticsItemMaintenanceView)
                {
                    Add(statisticsItemMaintenanceView);
                }


                return new OperationResult(OperationResultType.Success, "操作成功");
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
        }
        #endregion

        #region 删除
        public OperationResult Delete(Guid id)
        {
            PublicHelper.CheckArgument(id, "id");
            StatisticsItemMaintenance record = StatisticsItemMaintenanceRepository.Entities.FirstOrDefault(s => s.ID == id);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            if (IsBeRef(record) == "0")
            {
                if (StatisticsItemMaintenanceRepository.Delete(record) >= 0)
                {
                    return new OperationResult(OperationResultType.Success, "删除成功", record);
                }
                else
                {
                    return new OperationResult(OperationResultType.Error, "删除失败");
                }
            }
            else
            {
                return new OperationResult(OperationResultType.IsBeRef, "当前统计项已经被引用，不能修改！");
            }
        }

        private string IsBeRef(StatisticsItemMaintenance statisticsItemMaintenance)
        {
            IQueryable<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenance.ID);
            if (lstTotalMaintenanceDetail.Count() > 0)
            {
                return "1";
            }

            IQueryable<YearPlanDetails> lstYearPlanDetail = YearPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenance.ID);
            if (lstYearPlanDetail.Count() > 0)
            {
                return "1";
            }

            IQueryable<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(t => t.StatisticsItemID == statisticsItemMaintenance.ID);
            if (lstMonthPlanDetail.Count() > 0)
            {
                return "1";
            }

            return "0";
        }
        #endregion

        #region 排序
        public OperationResult SetOrder(Guid id, string upOrDown)
        {
            var exeResult = StatisticsItemMaintenanceRepository.SetOrder(StatisticsItemMaintenanceRepository.Entities, id, "OrderNo", upOrDown);  //执行向上向下操作
            return exeResult;
        }
        #endregion
    }
}